package util

import (
	"crypto/tls"
	"encoding/json"
	"io"
	"net/http"
	"strings"
)

func HttpGet(url string) (resp *http.Response, err error) {
	if strings.Contains(url, "https") {
		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		client := &http.Client{Transport: tr}
		resp, err = client.Get(url)
	} else {
		resp, err = http.Get(url)
	}
	return
}

func GetIpAddress() (ipAddress string, err error) {
	var (
		resp *http.Response
	)
	if resp, err = HttpGet("https://www.ip.cn/api/index?ip&type=0"); err == nil && resp != nil {
		if resultMap := RespTransformation(resp); resultMap != nil {
			ipAddress = resultMap["ip"].(string)
		}
	}
	return
}

func RespTransformation(response *http.Response) map[string]interface{} {
	var result map[string]interface{}
	body, err := io.ReadAll(response.Body)
	if err == nil {
		json.Unmarshal([]byte(string(body)), &result)
	}
	return result
}
